#include <wx/wx.h>
#include "taskbaricon.h"
#include "mainframe.h"
#include "../core/thememgr.h"

TaskBarIcon::TaskBarIcon(MainFrame* p_parent) {
	_p_parent = p_parent;
	_p_thememgr = &ThemeManager::get();
	
	
	wxIcon icon;
	wxBitmap& bmp = _p_thememgr->get_bitmap(_T("home-24.png"));
	
	icon.CopyFromBitmap(bmp);
	
	SetIcon(icon, _("Daodict - Running"));
	
	InitEvents();
}


void TaskBarIcon::InitEvents() {
	this->Connect(ID_SHOW_MAINWND, wxEVT_COMMAND_MENU_SELECTED, 
			(wxObjectEventFunction)&TaskBarIcon::OnShowMainWnd);
	this->Connect(ID_EXIT_MAINWND, wxEVT_COMMAND_MENU_SELECTED, 
			(wxObjectEventFunction)&TaskBarIcon::OnExitMainWnd);

	this->Connect(wxEVT_TASKBAR_LEFT_UP,
			(wxObjectEventFunction)&TaskBarIcon::OnClick);
	
}


// Overridables
wxMenu* TaskBarIcon::CreatePopupMenu()
{
    // Try creating menus different ways
    // TODO: Probably try calling SetBitmap with some XPMs here
    wxMenu* menu = new wxMenu;
    wxMenuItem* p_show_mainwnd = menu->Append(ID_SHOW_MAINWND, _("&Show Daodict"));
    menu->AppendSeparator();
    
    wxMenuItem* p_exit = new wxMenuItem(menu, ID_EXIT_MAINWND, _("E&xit"));
    wxBitmap& bmp = _p_thememgr->get_bitmap(_T("exit-24.png"));
    p_exit->SetBitmap(bmp);
    menu->Append(p_exit);
    
    p_show_mainwnd->SetBitmap(bmp);
    
    return menu;
}


void TaskBarIcon::OnShowMainWnd(wxCommandEvent& event) {
	_p_parent->Show();
	_p_parent->Raise();
}


void TaskBarIcon::OnExitMainWnd(wxCommandEvent& event) {
	_p_parent->Destroy();
}


#ifdef __WXMSW__
#include <wx/msw/private.h>

bool is_covered_by_foreign_wnd(wxTopLevelWindow* p_wnd) {
	int x,y,w,h;
	p_wnd->GetPosition(&x,&y);
	p_wnd->GetSize(&w, &h);
	
	POINT points[4] = { 
			{x+10, y+10}, // top left
			{x+w-10, y+10}, // top right
			{x+10, y+h-10}, // bottom left
			{x+w-10, y+h-10}, // bottom right
	};
	
	HWND h_cover_wnd = NULL;
	
	for (int i=0; i<4; i++) {
		h_cover_wnd = ::WindowFromPoint(points[i]);
		// wxMessageBox(wxString::Format(_("%d, %d"), points[i].x, points[i].y ));
		
		if (NULL==wxFindWinFromHandle(WXHWND(h_cover_wnd))) {
			return false;
		}
	}
	
	return true;
}
#elif __WXGTK__
	bool is_covered_by_foreign_wnd(wxTopLevelWindow* p_wnd) {
		return p_wnd->IsActive();
	}
#else
	bool is_covered_by_foreign_wnd(wxTopLevelWindow* p_wnd) {
		return true;
	}
#endif // __WXMSW__


void TaskBarIcon::OnClick(wxTaskBarIconEvent& event) {
	bool is_at_top = is_covered_by_foreign_wnd(_p_parent);
	
	if (false==_p_parent->IsShownOnScreen()) {
		_p_parent->Show();
		_p_parent->Raise();
		_p_parent->focus_search_ctrl();
		return;
	}

	if (false==is_at_top) {
		_p_parent->Show();
		_p_parent->Raise();
		_p_parent->focus_search_ctrl();
		return;
	}

	_p_parent->Hide();
}
